import { ImageUploaderTriggerContext } from '../ImageUploader/ImageUploaderTriggerContext';
import { useContext, useEffect, useRef, useState } from 'react';
import { Flex, Center, IconButton, Image } from '@chakra-ui/react';
import { FaRegTrashAlt } from 'react-icons/fa';
import { useStore } from '@nanostores/react';
import { $layerSrcList, $hideIndex } from '../store';
import LayerImages from './LayerImages';
export type CanvasSize = {
  width: number;
  height: number;
};
export default function ImagePreview() {
  const containerRef = useRef<HTMLDivElement>(null);

  const [containerSize, setContainerSize] = useState<CanvasSize>({
    width: 0,
    height: 0,
  });

  const layerSrcList = useStore($layerSrcList);
  const { file, setFile } = useContext(ImageUploaderTriggerContext);
  useEffect(() => {
    () => {
      file && URL.revokeObjectURL(file.preview);
    };
  }, [file]);
  useEffect(() => {
    if (!containerRef.current) {
      return;
    }
    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        if (entry.contentBoxSize) {
          const { width, height } = entry.contentRect;
          setContainerSize({ width, height });
        }
      }
    });

    resizeObserver.observe(containerRef.current);

    return () => {
      resizeObserver.disconnect();
    };
  }, []);
  return file ? (
    <Flex
      padding={1}
      position="relative"
      flexDirection="column"
      flexGrow="1"
      align="center"
      justify="center"
      h="full"
    >
      <Center
        width="full"
        height="full"
        maxWidth="full"
        maxHeight="calc(100% - 40px - 0.5rem)"
        ref={containerRef}
        position="relative"
      >
        {layerSrcList && layerSrcList.length ? (
          <LayerImages containerSize={containerSize} />
        ) : (
          <Image
            src={file.preview}
            maxWidth="full"
            maxHeight="full"
            height="full"
            objectFit="contain"
          />
        )}
      </Center>
      <Flex pt="2" justify="center">
        <IconButton
          icon={<FaRegTrashAlt />}
          boxSize={10}
          aria-label="clear image"
          onClick={() => setFile && setFile(null)}
        />
      </Flex>
    </Flex>
  ) : null;
}
